/* 
管理todos模块相关状态数据的redux模块
*/
// 同步action
export const addTodoAction = (title) => ({type: 'ADD_TODO', payload: title})
export const deleteTodoAction = id => ({type: 'DELETE_TODO', payload: id})
export const toggleTodoAction = id => ({type: 'TOGGLE_TODO', payload: id})
export const clearCompleteTodosAction = () => ({type: 'CLEAR_COMPLETE_TODOS'})
export const selectAllAction = isCheck => ({type: 'SELECT_ALL', payload: isCheck})

// 返回异步action的action creator
export const aysnAddAction = (title) => {
  return dispatch => {
    // 执行异步处理
    setTimeout(() => {
      // 分发同步action
      dispatch(addTodoAction(title))
    }, 1000);
  }
}

// reducer
const initState = JSON.parse(localStorage.getItem('todos_key')) || []
export default function todosReducer(state=initState, action) {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        {id: Date.now(), title: action.payload, complete: false},
        ...state
      ]
    case 'DELETE_TODO':
      return state.filter(todo => todo.id !== action.payload)
    case 'TOGGLE_TODO':
      return state.map(todo => {
        if (todo.id===action.payload) {
          return {...todo, complete: !todo.complete}
        }
        return todo
      })
    case 'CLEAR_COMPLETE_TODOS':
      return state.filter(todo => !todo.complete)
    case 'SELECT_ALL':
      return state.map(todo => ({...todo, complete: action.payload}))
    default:
      return state
  }
}
